<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\web\controller;

use app\common\model\Goods;
use app\common\model\GoodsCategory as GoodsCategoryModel;

class Index extends Base
{
    /**
     * 首页
     */
    public function index()
    {
        // 获取分类列表
        $categories = $this->getCategories();
        return $this->render('index', [
            'title'       => conf('site_subtitle'),
            'keywords'    => conf('site_keywords'),
            'description' => conf('site_desc'),
            'categories'  => $categories,
        ]);
    }

    /**
     * 404页面
     */
    public function notFound()
    {
        // 获取当前模板
        $template = $this->getCurrentTemplate();

        // 检查当前模板是否有404页面
        $template404Path = base_path() . "/app/web/view/{$template}/404.html";

        // 如果当前模板没有404页面，使用默认模板
        if (!file_exists($template404Path)) {
            $template = 'default';
        }

        // 随机获取一些推荐商品
        $recommendBooks = Goods::where('status', 1)
            ->orderRaw('RAND()')
            ->limit(4)
            ->select();

        // 返回404页面
        return $this->render('404', [
            'title'           => '页面不存在',
            'keywords'        => conf('site_keywords'),
            'description'     => conf('site_desc'),
            'recommend_books' => $recommendBooks,
        ]);
    }

    /**
     * 获取分类及其商品
     */
    private function getCategories()
    {
        $categories = GoodsCategoryModel::where([
            'status'  => 1,
            'pid'     => 0,
            'is_menu' => 1
        ])->order('sort desc, id desc')->field('id,name,pic,is_spec_filter,pinyin')->select();

        $list = [];
        foreach ($categories as $category) {
            // 获取分类商品数量
            $category->goods_count = $category->goods()->where([
                'status' => 1,
            ])->count();

            // 获取子分类
            $category->children = $this->getChildren($category->id);

            // 获取分类下的商品（限制12个）
            $category->goods = $this->getCategoryGoods($category->id, 15);

            $list[] = $category;
        }

        return $list;
    }

    /**
     * 获取子分类
     */
    private function getChildren($parentId)
    {
        $children = GoodsCategoryModel::where([
            'status' => 1,
            'pid'    => $parentId
        ])->field('id,name,pic,is_spec_filter,pinyin')->order('sort desc, id desc')->select()->each(function ($child) {
            $child->goods_count = $child->goods()->where([
                'status' => 1,
            ])->count();
            $child->children = $this->getChildren($child->id); // 递归获取下级分类
        });
        return $children;
    }

    /**
     * 获取分类商品
     */
    private function getCategoryGoods($cateId, $limit = 12)
    {
        // 获取当前分类及所有子分类的ID
        $cateIds = $this->getAllCateIds($cateId);

        return Goods::where([
            'status' => 1,
        ])->whereIn('cate_id', $cateIds)->order('sort desc, id desc')->limit($limit)->select();
    }

    /**
     * 获取分类及其所有子分类ID
     */
    private function getAllCateIds($cateId)
    {
        $ids = [$cateId]; // 初始包含当前分类ID

        // 查找直接子分类
        $children = GoodsCategoryModel::where([
            'status' => 1,
            'pid'    => $cateId
        ])->column('id');

        // 递归获取每个子分类的子分类
        foreach ($children as $childId) {
            $ids = array_merge($ids, $this->getAllCateIds($childId));
        }

        return $ids;
    }
}
